<template>
  <el-dialog model-value="dialogVisible" :title="dialogTitle" width="30%" @close="handleClose">

    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="树种名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <!-- <el-input v-model="form.status" /> -->
        <el-switch v-model="form.status" class="ml-2" inline-prompt active-text="正常" inactive-text="禁用"
          :active-value="1" :inactive-value="0"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"></el-switch>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="4" />
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>

import { defineEmits, defineProps, ref, watch } from "vue";
import api, { getServerUrl } from "@/util/request";
import { ElMessage } from 'element-plus'



const props = defineProps(
  {
    id: {
      type: Number,
      default: -1,
      required: true
    },
    dialogTitle: {
      type: String,
      default: '',
      required: true
    },
    dialogVisible: {
      type: Boolean,
      default: false,
      required: true
    }
  }
)


const form = ref({
  id: -1,
  name: "",
  code: "",
  remark: ""
})


const rules = ref({
  name: [
    { required: true, message: '请输入角色名称' }
  ],
  code: [
    { required: true, message: '请输入权限字符' }
  ]
})

const formRef = ref(null)

const initFormData = async (id) => {
  const res = await api.get("treeSpecies/action?id=" + id);
  form.value = res.data.data;
  // console.log(form.value)
}


watch(
  () => props.dialogVisible,
  () => {
    let id = props.id;
    if (id != -1) {
      initFormData(id)
    } else {
      form.value = {
        id: -1,
        name: "",
        code: "",
        remark: ""
      }

    }
  }
)


const emits = defineEmits(['update:modelValue', 'initTreeList'])

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let result = await api.post("treeSpecies/save", form.value);
      let data = result.data;
      if (data.code == 200) {
        ElMessage.success(data.msg)
        formRef.value.resetFields();
        emits("initTreeList")
        handleClose();
      } else {
        ElMessage.error(data.msg);
      }
    } else {
      console.log("fail")
    }
  })
}

</script>

<style scoped></style>
